import { warnTime } from './constant.js'
// import { SyncPost } from '/@/api/linxyun/base/index.ts'
import IFileClient from './file_client_interface.js'
import { getGUID } from './guid.js'
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

const COS = () => ({})

export default class FileClient_TX extends IFileClient {
	constructor(fileConfig) {
		super(fileConfig)
	}

	getFileFullUrl(fileID) {
		return 'http://' + fileID
	}

	async uploadContent(fileName, content) {
		const postData = this._fileConfig.postData
		const credentials = postData.credentials
		const that = this
		const afile = content //arguments[0].file
		const cos = await new COS({
			getAuthorization: function (options, callback) {
				callback({
					TmpSecretId: credentials.tmpSecretId,
					TmpSecretKey: credentials.tmpSecretKey,
					XCosSecurityToken: credentials.sessionToken,
					// ========
					StartTime: postData.startTime,
					ExpiredTime: postData.expiredTime
				})
			}
		})
		let key = getGUID()
		if (arguments[0].key) {
			key = arguments[0].key
		}
		//console.log('0000000: key', key)
		await cos.putObject(
			{
				...that._fileConfig.setting,
				Key: key,
				StorageClass: 'STANDARD',
				Body: afile, // 上传文件对象
				onProgress: function () {} //onProgress: function (progressData) {}
			},
			function (err, data) {
				console.log('put obj', err || data)
				if (data && data.statusCode === 200) {
					return that.getFileFullUrl(data.Location)
				} else {
					return null
				}
			}
		)
	}

	async deleteFile(url) {
		console.log('[Debug][File]delete file, url: ', url)
		if (!(await this.init())) {
			console.error('[Error][File][deleteFile]Init file client fail.')
			return null
		}
	}

	async checkToken() {
		if (!this._fileConfig || !this._fileConfig.postData) {
			return false
		}
		if (!this.isTokenExpired()) {
			return true
		}
		let res = await httpReqeust.SyncPost(this._genTokenUrl)
		if (!res || res.code !== '0000') {
			return false
		}
		if (!res.credential || res.credential === '') {
			console.log('[getFileConfig]Failed to init file server config.')
			return null
		}

		this._fileConfig.postData = res.credential
		return true
	}

	isTokenExpired() {
		if (!this._fileConfig.postData) {
			return true
		}

		const { expiredTime } = this._fileConfig.postData
		const nowTime = Math.floor(new Date().getTime() / 1000)
		return expiredTime - warnTime < nowTime
	}
}
